package com.gitee.base.modules;

import com.gitee.base.utils.JsonVo;
import com.gitee.base.utils.Kit;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;

@Controller
@Validated
public class LoginController {

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha();
        captcha.setLen(3);
        captcha.getArithmeticString();
        captcha.text();
        CaptchaUtil.out(captcha,request, response);
    }

    @PostMapping("/loginDo")
    @ResponseBody
    public JsonVo loginDo(HttpServletRequest request, HttpServletResponse response, @NotBlank String username, @NotBlank String password,
                          @NotBlank String verifyCode, @RequestParam(defaultValue = "0") int rememberMe){
        if (!CaptchaUtil.ver(verifyCode, request)) {
            CaptchaUtil.clear(request);
            return JsonVo.fail(500,"验证码不正确");
        }
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(usernamePasswordToken);
        if(subject.isAuthenticated()){
            Kit.addCookieToken(response,Kit.createToken(username),rememberMe==1?14*86400:-1);
            return JsonVo.success();
        }
        return JsonVo.fail(500,"登录失败");
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        SecurityUtils.getSubject().logout();
        Kit.clearCookie(response);
        return "login";
    }

    @GetMapping(value = {"","/"})
    public String index(ModelMap modelMap){
        modelMap.put("os",System.getProperty("os.name")+" "+System.getProperty("sun.os.patch.level"));
        modelMap.put("osArch",System.getProperty("os.arch"));
        modelMap.put("jdk",System.getProperty("java.version"));
        modelMap.put("totalMemory",Runtime.getRuntime().totalMemory()/1024/1024 +"MB");
        modelMap.put("freeMemory",Runtime.getRuntime().freeMemory()/1024/1024 +"MB");
        modelMap.put("maxMemory",Runtime.getRuntime().maxMemory()/1024/1024 +"MB");
        return "index";
    }
}
